package com.ruoyi.common.annotation;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.util.UUID;

@Component
public class UUIDBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 获取bean的类
        Class<?> clazz = bean.getClass();
        
        // 遍历所有字段
        ReflectionUtils.doWithFields(clazz, field -> {
            // 检查字段是否包含UUID注解
            if (field.isAnnotationPresent(com.ruoyi.common.annotation.UUIDGenerated.class)) {
                // 确保字段类型是String
                if (field.getType().equals(String.class)) {
                    // 设置字段可访问
                    ReflectionUtils.makeAccessible(field);
                    
                    // 如果字段值为null，则生成UUID并设置
                    if (ReflectionUtils.getField(field, bean) == null) {
                        String uuid = UUID.randomUUID().toString();
                        ReflectionUtils.setField(field, bean, uuid);
                    }
                }
            }
        });
        
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}